<template>
  <div class="employee-management">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>员工管理</span>
          <el-button 
            type="primary" 
            @click="handleAddEmployee"
            v-if="hasAddPermission"
          >
            添加员工
          </el-button>
        </div>
      </template>

      <!-- 搜索条件 -->
      <div class="search-form">
        <el-form :model="queryParams" inline>
          <el-form-item label="搜索关键词">
            <el-input
              v-model="queryParams.keyword"
              placeholder="请输入职位、部门或员工编号"
              clearable
              @keyup.enter="handleSearch"
            />
          </el-form-item>
          <el-form-item label="职位">
            <el-input
              v-model="queryParams.position"
              placeholder="请输入职位"
              clearable
            />
          </el-form-item>
          <el-form-item label="部门">
            <el-input
              v-model="queryParams.department"
              placeholder="请输入部门"
              clearable
            />
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
              <el-option label="在职" :value="1" />
              <el-option label="离职" :value="0" />
              <el-option label="待入职" :value="2" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 员工列表 -->
      <el-table :data="employeeList" v-loading="loading" stripe>
        <el-table-column prop="username" label="用户名" min-width="120" />
        <el-table-column prop="realName" label="真实姓名" min-width="120" />
        <el-table-column prop="position" label="职位" min-width="120" />
        <el-table-column prop="department" label="部门" min-width="120" />
        <el-table-column prop="employeeNo" label="员工编号" min-width="120" />
        <el-table-column prop="propertyCompanyName" label="所属公司" min-width="150">
          <template #default="{ row }">
            {{ row.propertyCompanyName || '暂无物业公司' }}
          </template>
        </el-table-column>
        <el-table-column prop="joinDate" label="入职日期" min-width="120">
          <template #default="{ row }">
            {{ formatDate(row.joinDate) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button 
              size="small" 
              @click="handleEditEmployee(row)"
              v-if="hasEditPermission"
            >
              编辑
            </el-button>
            <el-button 
              size="small" 
              type="danger" 
              @click="handleRemoveEmployee(row)"
              v-if="hasDeletePermission"
            >
              移除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        v-model:current-page="queryParams.current"
        v-model:page-size="queryParams.size"
        :total="total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <!-- 添加员工弹窗 -->
    <AddEmployeeDialog 
      v-model:visible="addDialogVisible"
      :property-company-id="propertyCompanyId"
      @success="handleAddSuccess"
    />

    <!-- 编辑员工弹窗 -->
    <EditEmployeeDialog 
      v-model:visible="editDialogVisible"
      :property-company-id="propertyCompanyId"
      :employee="currentEmployee"
      @success="handleEditSuccess"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { ElMessageBox } from 'element-plus'
import { useRoute } from 'vue-router'
import { propertyEmployeeApi } from '@/api/property/employee'
import AddEmployeeDialog from './components/AddEmployeeDialog.vue'
import EditEmployeeDialog from './components/EditEmployeeDialog.vue'
import type { EmployeeVO } from '@/api/property/employee/types'
import { showMessage } from '@/utils/message'

// 路由参数
const route = useRoute()
const propertyCompanyId = computed(() => Number(route.params.propertyCompanyId))

// 响应式数据
const loading = ref(false)
const employeeList = ref<EmployeeVO[]>([])
const total = ref(0)
const queryParams = ref({
  current: 1,
  size: 10,
  keyword: '',
  position: '',
  department: '',
  status: undefined as number | undefined
})

// 弹窗控制
const addDialogVisible = ref(false)
const editDialogVisible = ref(false)
const currentEmployee = ref<EmployeeVO | null>(null)

// 权限控制
const hasAddPermission = ref(true) // TODO: 从权限系统获取
const hasEditPermission = ref(true) // TODO: 从权限系统获取
const hasDeletePermission = ref(true) // TODO: 从权限系统获取

// 生命周期
onMounted(() => {
  loadEmployeeList()
})

// 方法
const loadEmployeeList = async () => {
  try {
    loading.value = true
    const { data } = await propertyEmployeeApi.getPropertyCompanyEmployees(
      propertyCompanyId.value,
      queryParams.value
    )
    employeeList.value = data.records
    total.value = data.total
  } catch (error) {
    showMessage({ type: 'error', message: '加载员工列表失败' })
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  queryParams.value.current = 1
  loadEmployeeList()
}

const handleReset = () => {
  queryParams.value = {
    current: 1,
    size: 10,
    keyword: '',
    position: '',
    department: '',
    status: undefined
  }
  loadEmployeeList()
}

const handleSizeChange = (size: number) => {
  queryParams.value.size = size
  queryParams.value.current = 1
  loadEmployeeList()
}

const handleCurrentChange = (current: number) => {
  queryParams.value.current = current
  loadEmployeeList()
}

const handleAddEmployee = () => {
  addDialogVisible.value = true
}

const handleAddSuccess = () => {
  addDialogVisible.value = false
  showMessage({ type: 'success', message: '添加员工成功' })
  loadEmployeeList()
}

const handleEditEmployee = (row: EmployeeVO) => {
  currentEmployee.value = row
  editDialogVisible.value = true
}

const handleEditSuccess = () => {
  editDialogVisible.value = false
  currentEmployee.value = null
  showMessage({ type: 'success', message: '更新员工信息成功' })
  loadEmployeeList()
}

const handleRemoveEmployee = async (row: EmployeeVO) => {
  try {
    await ElMessageBox.confirm(
      `确定要移除员工"${row.realName}"吗？`,
      '确认移除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    await propertyEmployeeApi.removeEmployeeFromPropertyCompany(
      propertyCompanyId.value,
      row.id
    )
    
    showMessage({ type: 'success', message: '移除员工成功' })
    loadEmployeeList()
  } catch (error) {
    if (error !== 'cancel') {
      showMessage({ type: 'error', message: '移除员工失败' })
    }
  }
}

// 工具方法
const formatDate = (date: string | null) => {
  if (!date) return ''
  return new Date(date).toLocaleDateString()
}

const getStatusType = (status: number) => {
  switch (status) {
    case 0: return 'danger'
    case 1: return 'success'
    case 2: return 'warning'
    default: return 'info'
  }
}

const getStatusText = (status: number) => {
  switch (status) {
    case 0: return '离职'
    case 1: return '在职'
    case 2: return '待入职'
    default: return '未知'
  }
}
</script>

<style scoped>
.employee-management {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.search-form .el-form-item {
  margin-bottom: 0;
}
</style> 